<template>
  <h2>覆盖前一张图片</h2>
  <el-upload
    ref="upload"
    class="upload-demo"
    action="http://goapi.sanjitian.cn/api/files"
    :limit="1"
    :on-exceed="handleExceed"
    :auto-upload="false"
    :headers="headers"
    :data="extraData"
    name="file"
    accept="image/*"
    :on-success="handleAvatarSuccess"
    :show-file-list="false"
  >
    <template #trigger>
      <el-button type="primary">select file</el-button>
    </template>
    <el-button class="ml-3" type="success" @click="submitUpload"> upload to server </el-button>
    <template #tip>
      <div class="el-upload__tip text-red">limit 1 file, new file will cover the old file</div>
    </template>
  </el-upload>
  <div class="my-img-list">
    <img v-for="item in myImgList" :key="item.id" :src="item.filePathCos" :alt="item.fileType" />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
export interface IResponseImageInfo {
  code: string
  data: IFileInfo
  msg: string
}
export interface IFileInfo {
  fileExtension: string
  filePathCos: string
  fileSize: string
  fileType: string
  fileUse: string
  id: number
  mineType: string
  uploadTime: string
}

const myImgList = ref<IFileInfo[]>([])

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response: IResponseImageInfo,
  uploadFile
) => {
  console.log(uploadFile, '#uploadFile')
  console.log(response, '#response')
  myImgList.value?.push(response.data)
}

const headers = {
  Authorization:
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySW5mbyI6eyJ1c2VySWQiOjEwNjgsInVzZXJuYW1lIjoiQ3VpTWVuZ2ppYW8iLCJuaWNrbmFtZSI6IuW0lOaipuWohyIsImRlcHRJZCI6MSwicm9sZXMiOiJBRE1JTiJ9LCJpc3MiOiJkeXM2MjMwIiwiZXhwIjoxNzMxNDM4NTA2LCJuYmYiOjE3MzE0MDI1MDYsImlhdCI6MTczMTQwMjUwNn0.0dUF4oa_OiDYzVE2V1Cgic8sMlNampvOXAibFLvaTO8' // 如果需要 Token 认证
}
const extraData = {}

const upload = ref<UploadInstance>()

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

const submitUpload = () => {
  upload.value!.submit()
}
</script>

<style lang="scss" scoped>
.my-img-list {
  width: 100%;
  height: 200px;
  display: flex;
  img {
    width: 200px;
    height: 200px;
    object-fit: contain;
    border: 1px solid #ccc;
  }
}
</style>
